package org.example.travel_web.service.impl;

import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.yulichang.wrapper.MPJLambdaWrapper;
import jakarta.annotation.Resource;
import org.example.travel_web.dto.PageResult;
import org.example.travel_web.dto.route.*;
import org.example.travel_web.entity.*;
import org.example.travel_web.enums.Type;
import org.example.travel_web.exception.RunException;
import org.example.travel_web.mapper.CommentsMapper;
import org.example.travel_web.mapper.RoutesMapper;
import org.example.travel_web.service.RouteDetailsService;
import org.example.travel_web.service.RoutesService;
import org.example.travel_web.service.UserAttrService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * @author 23591
 * @description 针对表【travel_routes(用于存储旅游路线的基本信息)】的数据库操作Service实现
 * @createDate 2025-01-21 15:58:16
 */
@Service
public class RoutesServiceImpl extends ServiceImpl<RoutesMapper, RoutesET>
        implements RoutesService {

    @Resource
    private CommentsMapper commentMapper;
    @Resource
    private RouteDetailsService routeDetailsService;
    @Resource
    private UserAttrService userAttrService;

    @Override
    public PageResult<PageResp> pageResult(RoutePageReq req) {
        MPJLambdaWrapper<RoutesET> wrapper = new MPJLambdaWrapper<RoutesET>()
                .selectAll(RoutesET.class)
                .selectAs(RouteCategoriesET::getName, PageResp::getCategoryName);
        if (StrUtil.isNotBlank(req.getTitle())) {
            wrapper.like(RoutesET::getTitle, req.getTitle());
        }
        if (req.getCategoryId() != null) {
            wrapper.eq(RoutesET::getCategoryId, req.getCategoryId());
        }
        wrapper.leftJoin(RouteCategoriesET.class, RouteCategoriesET::getCategoryId, RouteCategoriesET::getCategoryId);
        wrapper.orderByDesc(RoutesET::getCreatedAt);
        Page<PageResp> page = getBaseMapper().selectJoinPage(new Page<>(req.getPage(), req.getSize()), PageResp.class, wrapper);
        return PageResult.of(page.getTotal(), page.getCurrent(), page.getSize(), page.getRecords());
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void addRoutes(RouteReq req) {
//        if (req.getDetails() == null || req.getDays() != req.getDetails().size()) {
//            throw new RunException("天数与行程安排不匹配");
//        }
        LambdaQueryWrapper<RoutesET> wrapper = new LambdaQueryWrapper<RoutesET>()
                .eq(RoutesET::getTitle, req.getTitle());
        if (exists(wrapper)) {
            throw new RunException("标题已存在");
        }
        RoutesET routesET = BeanUtil.toBean(req, RoutesET.class);
        if (!save(routesET)) {
            throw new RunException("新增失败");
        }
//        List<RouteDetailsET> list = req.getDetails().stream().map(e -> {
//            RouteDetailsET bean = BeanUtil.toBean(e, RouteDetailsET.class);
//            bean.setRouteId(routesET.getRouteId());
//            return bean;
//        }).toList();
//        if (!routeDetailsService.saveBatch(list)) {
//            throw new RunException("新增失败");
//        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateRoutes(RouteReq req) {
//        if (req.getDetails() == null || req.getDays() != req.getDetails().size()) {
//            throw new RunException("天数与行程安排不匹配");
//        }
        if (req.getRouteId() == null) {
            throw new RunException("路线id不能为空");
        }
        LambdaQueryWrapper<RoutesET> wrapper = new LambdaQueryWrapper<RoutesET>()
                .eq(RoutesET::getTitle, req.getTitle())
                .ne(RoutesET::getRouteId, req.getRouteId());
        if (exists(wrapper)) {
            throw new RunException("标题已存在");
        }
        RoutesET routesET = BeanUtil.toBean(req, RoutesET.class);
        if (!updateById(routesET)) {
            throw new RunException("修改失败");
        }
//        LambdaQueryWrapper<RouteDetailsET> removeWrapper = new LambdaQueryWrapper<RouteDetailsET>()
//                .eq(RouteDetailsET::getRouteId, req.getRouteId());
//        if (!routeDetailsService.remove(removeWrapper)) {
//            throw new RunException("删除失败");
//        }
//        if (!routeDetailsService.saveBatch(req.getDetails().stream().map(e -> {
//            RouteDetailsET bean = BeanUtil.toBean(e, RouteDetailsET.class);
//            bean.setRouteId(routesET.getRouteId());
//            return bean;
//        }).toList())) {
//            throw new RunException("新增失败");
//        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteRoutes(Integer[] ids) {
        if (!removeByIds(List.of(ids))) {
            throw new RunException("删除失败");
        }
        LambdaQueryWrapper<CommentsET> wrapper = new LambdaQueryWrapper<CommentsET>()
                .eq(CommentsET::getType, Type.ROUTE)
                .in(CommentsET::getRelateId, List.of(ids));
        if (commentMapper.selectCount(wrapper) > 0 && commentMapper.delete(wrapper) < 1) {
            throw new RunException("删除失败");
        }
//        LambdaQueryWrapper<RouteDetailsET> removeWrapper = new LambdaQueryWrapper<RouteDetailsET>()
//                .in(RouteDetailsET::getRouteId, List.of(ids));
//        if (!routeDetailsService.remove(removeWrapper)) {
//            throw new RunException("删除失败");
//        }
        LambdaQueryWrapper<UserAttrET> attrWrapper = new LambdaQueryWrapper<>();
        attrWrapper.eq(UserAttrET::getType, Type.ROUTE);
        attrWrapper.in(UserAttrET::getRelateId, List.of(ids));
        if (userAttrService.count(attrWrapper) > 0 && !userAttrService.remove(attrWrapper)) {
            throw new RunException("删除失败");
        }
    }

    @Override
    public RouteDetailResp getRouteDetail(Integer id) {
        MPJLambdaWrapper<RoutesET> wrapper = new MPJLambdaWrapper<RoutesET>()
                .selectAll(RoutesET.class)
                .selectAs(RouteCategoriesET::getName, PageResp::getCategoryName);
        wrapper.eq(RoutesET::getRouteId, id);
        wrapper.leftJoin(RouteCategoriesET.class, RouteCategoriesET::getCategoryId, RouteCategoriesET::getCategoryId);
        RouteDetailResp detailResp = getBaseMapper().selectJoinOne(RouteDetailResp.class, wrapper);
        if (detailResp == null) {
            throw new RunException("路线不存在");
        }
//        LambdaQueryWrapper<RouteDetailsET> detailWrapper = new LambdaQueryWrapper<>();
//        detailWrapper.eq(RouteDetailsET::getRouteId, id);
//        List<RouteDetailsET> routeDetails = routeDetailsService.list(detailWrapper);
//        detailResp.setDetails(BeanUtil.copyToList(routeDetails, Detail.class));
        if (StpUtil.isLogin()){
            LambdaQueryWrapper<UserAttrET> routeWrapper = new LambdaQueryWrapper<>();
            routeWrapper.eq(UserAttrET::getUid, StpUtil.getLoginIdAsLong());
            routeWrapper.eq(UserAttrET::getType, Type.ROUTE);
            routeWrapper.eq(UserAttrET::getRelateId, id);
            detailResp.setIsCollection(userAttrService.exists(routeWrapper));
        }
        return detailResp;
    }

    @Override
    public PageResult<UserRoutePageResp> userPageResult(UserRoutePageReq req) {
        LambdaQueryWrapper<RoutesET> wrapper = new LambdaQueryWrapper<>();
        if (req.getCategoryId() != null) {
            wrapper.eq(RoutesET::getCategoryId, req.getCategoryId());
        }
        if (StrUtil.isNotBlank(req.getKeyword())) {
            wrapper.like(RoutesET::getTitle, req.getKeyword());
        }
        wrapper.orderByDesc(RoutesET::getCreatedAt);
        Page<RoutesET> page = page(new Page<>(req.getPage(), req.getSize()), wrapper);
        return PageResult.of(page.getTotal(), page.getCurrent(), page.getSize(), BeanUtil.copyToList(page.getRecords(), UserRoutePageResp.class));
    }
}




